<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from "vue";
import Highcharts from "highcharts/highcharts";//highcharts版本11.4.8
import Highcharts3d from "highcharts/highcharts-3d";//highcharts版本11.4.8
// import HighchartsMore from 'highcharts/highcharts-more'
// HighchartsMore(Highcharts)
Highcharts3d(Highcharts);
// 定义 props
const props = defineProps({
  options: {
    type: Object,
    required: true,
    default: () => ({}),
  },
});

// 初始化额外模块

// refs
const chartContainer = ref(null);
const chart = ref(null);

// 方法
const initChart = () => {
  try {
    if (!chartContainer.value) {
      console.error("Chart container not found");
      return;
    }

    const HighchartsInstance = Highcharts || window.Highcharts;

    if (!HighchartsInstance) {
      console.log("Highcharts library not loaded");
    }

    chart.value = HighchartsInstance.chart(chartContainer.value, props.options);
  } catch (error) {
    console.error("图表初始化错误:", error);
  }
};

const updateChart = () => {
  if (chart.value) {
    chart.value.update(props.options);
  } else {
    initChart();
  }
};

// 监听 options 变化
watch(
  () => props.options,
  () => {
    nextTick(() => {
      updateChart();
    });
  },
  { deep: true }
);

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    initChart();
  });
});

onBeforeUnmount(() => {
  if (chart.value) {
    chart.value.destroy();
  }
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
